"""
Description :  
Author :       songtao
date：         2023/3/21
"""
import datetime
from elasticsearch import Elasticsearch
from zs_config.common import GenericLoader


class EsConfigLoader(GenericLoader):
    def __init__(self, bootstrap_cfg):
        super().__init__(bootstrap_cfg)

    def get_es_conn(self):
        es_conn = None
        ignore_error = self.bootstrap_cfg.config.es.ignore_error
        es_uri = self.bootstrap_cfg.config.es.uri
        if es_uri:
            try:
                es_conn = Elasticsearch(hosts=es_uri)
            except Exception:
                if not ignore_error:
                    raise
        return es_conn

    @property
    def doc_info(self):
        es_uri = self.bootstrap_cfg.config.es.uri
        config_index = self.bootstrap_cfg.config.es.index
        config_doc_id = self.bootstrap_cfg.config.es.doc_id
        if not (config_index and config_doc_id and es_uri):
            return {}
        doc_info = {'index': config_index, 'id': config_doc_id}
        return doc_info

    def load(self):
        ret = []
        doc_info = self.doc_info
        if not doc_info:
            return ret
        es_conn = self.get_es_conn()
        ignore_error = self.bootstrap_cfg.config.es.ignore_error
        try:
            es_config = es_conn.get(ignore=[404], **doc_info)
            if es_config['found']:
                config = es_config['_source']['config']
                ret.append({'id': self.get_file_type(), 'obj': config})
        except Exception:
            if not ignore_error:
                raise
        finally:
            es_conn.close()
        return ret

    def get_file_type(self):
        return 'es'

    def put(self, config, name=None, version=None):
        """
        :param config: 配置具体内容
        :param name: 配置来源或者标识
        :param version: 配置文件的版本
        :return:
        """

        doc_info = self.doc_info
        if not doc_info:
            return

        doc = {'config': config, 'update_stamp': datetime.datetime.now().isoformat()}
        if name:
            doc['name'] = name
        if version:
            doc['version'] = version
        with self.get_es_conn() as es_conn:
            es_conn.index(body=doc, **doc_info)

    def delete(self):
        doc_info = self.doc_info
        if not doc_info:
            return
        with self.get_es_conn() as es_conn:
            es_conn.delete(ignore=[404], **doc_info)
